#!/usr/bin/env python
# -*- coding: utf-8 -*-

from __future__ import print_function
import mp3play
import os

from downloader import Downloader
import config
from logger import logger
import utils


def check_player(default=None):
    def pre_wrapper(func):
        def wrapper(player, *args, **kwargs):
            if player._player:
                return func(player, *args, **kwargs)
            else:
                logger.warning('No player exists')
                return default

        return wrapper

    return pre_wrapper


class Player(object):
    def __init__(self, downloader=None):
        super(Player, self).__init__()
        self._downloader = downloader and downloader or Downloader()
        self._player = None

    def _get_song_full_filename(self, song):
        cache_file = os.path.join(config.CACHE_DIR, song.mp3_file)
        download_file = os.path.join(config.DOWNLOAD_DIR, song.mp3_file)
        if os.path.exists(cache_file):
            return cache_file
        elif os.path.exists(download_file):
            return download_file
        else:
            return ''

    def play(self, song):
        song_filename = self._get_song_full_filename(song)
        if song_filename == '':
            results = self._downloader.add_task(song)
            if not results:
                logger.warning('Failed to play song: %s' % song.mp3_file)
                return False
        song_filename = song_filename.replace('\\', '\\\\')
        logger.info('play song: %s - %s %s ' %
                    (song.title, song.speak, song_filename))
        self._player = mp3play.load(song_filename)
        self._player.play()

    @check_player()
    def pause(self):
        logger.debug('%s - %s' % (utils.format_time(self.position()),
                                  utils.format_time(self.seconds())))
        self._player.pause()

    @check_player()
    def unpause(self):
        self._player.unpause()

    @check_player()
    def toggle(self):
        if self.isplaying():
            self._player.pause()
        else:
            self._player.unpause()

    @check_player()
    def stop(self):
        self._player.stop()

    @check_player(False)
    def isplaying(self):
        return self._player.isplaying()

    @check_player(True)
    def ispaused(self):
        return self._player.ispaused()

    @check_player(0)
    def seconds(self):
        return self._player.seconds()

    @check_player()
    def volumn(self, level):
        if level >= 0 and level <= 100:
            self._player.volume(level)

    @check_player(0)
    def position(self):
        return self._player.position()
